import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


# img_dir = '../../../../../large_data/CV2/lesson/Day06'
# img_name = 'hammer.jpg'
img_dir = '../../../../../large_data/pic'
# img_name = 'DSC05039.JPG'
# img_name = 'DSC05022_1.JPG'
# img_name = 'dog.jpg'
# img_name = 'dog_bird.jpg'
img_name = 'football.jpg'
img_path = os.path.join(img_dir, img_name)

spr = 2
spc = 4
spn = 0
plt.figure(figsize=[14, 6])

sep('load')
img = cv.imread(img_path, cv.IMREAD_COLOR)
# img = cv.resize(img, None, fx=0.1, fy=0.1, interpolation=cv.INTER_CUBIC)
print('original shape', img.shape)
H, W, _ = img.shape
H2 = (H - 1) // 2
W2 = (W - 1) // 2
my_show_img(img, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))
img_hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)

sep('roi')
roi = img[209:311, 0:157]
my_show_img(roi, 'roi', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))
roi_hsv = cv.cvtColor(roi, cv.COLOR_BGR2HSV)

sep('BackProject')
hist_roi_hsv = cv.calcHist([roi_hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])  # ATTENTION 1st param is images, pl, [img]
print_numpy_ndarray_info(hist_roi_hsv, 'hist_roi_hsv')
hist_roi_hsv_show = hist_roi_hsv.copy()
cv.normalize(hist_roi_hsv_show, hist_roi_hsv_show, 0, 1, cv.NORM_MINMAX)
my_show_img(hist_roi_hsv_show, 'hist_roi_hsv_show', cmap='gray')
B = cv.calcBackProject([img_hsv], [0, 1], hist_roi_hsv, [0, 180, 0, 256], 1)  # ATTENTION 1st param is images, pl, [img]
print_numpy_ndarray_info(B, 'B')
my_show_img(B, 'B', cmap='gray')
spn += 1
plt.subplot(spr, spc, spn)
plt.hist(B.ravel(), 256)
plt.title('B hist')

sep('filter2d to B')
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
B = cv.filter2D(B, -1, kernel)
print_numpy_ndarray_info(B, 'B filtered')
my_show_img(B, 'B filtered', cmap='gray')
spn += 1
plt.subplot(spr, spc, spn)
plt.hist(B.ravel(), 256)
plt.title('B filtered hist')

sep('Apply mask')
filtered = cv.bitwise_and(img, img, mask=B)
my_show_img(filtered, 'filtered', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))
# my_show_img(img, 'img', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

plt.show()
